from datetime import datetime
from loguru import logger
from celery import Celery

from apis_module.dao.reviews_dao import ReviewsDao
from apis_module.model.look_model import ReviewsLookModel
from config.env import JwtConfig
from config.get_db import get_db
from config.get_redis import RedisUtil

# celery_app = Celery(__name__, include=['apis_module.tasks'])


# @celery_app.task(name='update_look_reviews_cache_task')
async def update_look_reviews_cache_task():
    redis = await RedisUtil.create_redis_pool()
    # fetch redis data
    cache_list = []
    ttl = JwtConfig.REDIS_TOKEN_EXPIRE_MINUTES
    keys = await redis.keys('reviews_look:')
    if len(keys) > 0:
        totals = await redis.mget(keys)
        pipeline = redis.pipeline()

        for key, total in zip(keys, totals):
            # update cache's ttl by keys
            await pipeline.expire(key, ttl)
            # set model object
            model: ReviewsLookModel = ReviewsLookModel()
            model.reviews_id = key.decode().split(":")[1]
            model.look_total = int(total)
            model.last_update_time = datetime.now()
            cache_list.append(model)
        await pipeline.execute()

        try:
            result: bool = ReviewsDao.batch_add_looks(get_db(), cache_list)
            if result:
                logger.info('点击量缓存更新成功')
        except Exception as e:
            logger.error('点击量缓存更新失败')
            logger.error(e)
